package com.pdg.android.splorr.states;

import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.pdg.android.common.ParentedBase;
import com.pdg.android.common.State;
import com.pdg.android.splorr.R;
import com.pdg.android.splorr.SplorrActivity;
import com.pdg.android.splorr.data.Game;
import com.pdg.android.splorr.data.Room;
import com.pdg.android.splorr.data.RoomItem;
import com.pdg.android.splorr.data.enums.GameState;

public class RoomItemsState extends
State<Game, SplorrActivity, GameState>{

	private class TakeItemClickListener extends ParentedBase<RoomItemsState> implements View.OnClickListener{
		
		private int itemIndex;

		public TakeItemClickListener(int theItemIndex, RoomItemsState theParent) {
			super(theParent);
			setItemIndex(theItemIndex);
		}

		private void setItemIndex(int theItemIndex) {
			itemIndex=theItemIndex;
		}
		
		public int getItemIndex(){
			return itemIndex;
		}

		public void onClick(View v) {
			getParent().takeItem(getItemIndex());
		}

		
	}
	
	public RoomItemsState(Game theData, SplorrActivity theMachine) {
		super(theData, theMachine, GameState.ROOM_ITEMS);
	}

	public void takeItem(int itemIndex) {
		getData().takeItem(itemIndex);
		refreshDisplay();
	}

	@Override
	protected void onInitialize() {
	}

	@Override
	protected void onEnter() {
		getMachine().setContentView(R.layout.room_items);
		refreshDisplay();
	}

	private void refreshDisplay() {
		Room theRoom = getData().getCurrentRoom();
		TextView tv = (TextView)getMachine().findViewById(R.id.title);
		tv.setText(getData().getCurrentRoomSummary());
		
		TableLayout tl = (TableLayout)getMachine().findViewById(R.id.table);
		
		tl.removeAllViews();
		
		for(int theIndex=0;theIndex<theRoom.getItemCount();++theIndex){
			RoomItem theItem = theRoom.getItems().get(theIndex);
			
			if(theItem.isHidden()){
				continue;
			}
			
			TableRow tr = new TableRow(getMachine());
			tv = new TextView(getMachine());
			tv.setText(theItem.getName());
			
			tr.addView(tv);
			
			Button button = new Button(getMachine());
			
			button.setText(R.string.button_take);
			button.setOnClickListener(new TakeItemClickListener(theIndex,this));
			
			tr.addView(button);
			
			tl.addView(tr);
			
		}
		
	}

	@Override
	protected void onLeave() {
	}

	@Override
	protected void onCleanUp() {
	}

	@Override
	protected void onButtonPressed(int theButtonId) {
		switch(theButtonId){
			case R.id.button_back:
				getMachine().setCurrent(GameState.ROOM_SUMMARY);
				break;
		}
	}

}
